package com.mrd.util;

import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FormBeanUtil {
  static {
    // 在封装之前 注册转换器
    ConvertUtils.register(new DateTimeConverter(), java.util.Date.class);
  }

  /**
   * 请求信息封装到对象
   * 
   * @param request 请求信息
   * @param clazz 封装对象
   */
  @SuppressWarnings("unchecked")
  public static <T> T get(Map<String, Object> paramMap, Class<T> clazz) {
    if (paramMap == null)
      throw new IllegalArgumentException("FormBeanUtil.get中的request为空");
    T obj = null;
    try {
      obj = clazz.newInstance();
      BeanUtils.populate(obj, paramMap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return obj;
  }

  public static <T> T getFromLinkMap(LinkedHashMap<String, String> paramMap, Class<T> clazz) {
    if (paramMap == null)
      throw new IllegalArgumentException("FormBeanUtil.get中的request为空");
    T obj = null;
    try {
      obj = clazz.newInstance();
      BeanUtils.populate(obj, paramMap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return obj;
  }

  /**
   * 将分页组件参数转换为数据库模型对象
   * 
   * @author han
   * @param jqgrid
   * @param clazz
   * @return
   */
  public static <T> T getEntityFromJqgrid(Jqgrid jqgrid, Class<T> clazz) {
    T obj = null;
    try {
      Map<String, Object> parameterMap = new HashMap<>();

      // 组装查询条件
      Filter filter = jqgrid.getFilters();
      if (filter != null) {
        List<SearchRule> searchRuleList = filter.getRules();
        if (CollectionUtils.isNotEmpty(searchRuleList)) {
          for (SearchRule searchRule : searchRuleList) {
            parameterMap.put(searchRule.getField(), searchRule.getData());
          }
        }
      }
      obj = clazz.newInstance();
      BeanUtils.populate(obj, parameterMap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return obj;
  }
}
